<?php

/**
 * 用户管理
 */
namespace app\topics\model;

use app\system\model\SystemModel;

class TopicsUserModel extends SystemModel {

    protected $infoModel = [
        'pri' => 'user_id',
        'validate' => [
            'role_id' => [
                'empty' => ['', '角色不正确!', 'must', 'all'],
            ],
            'username' => [
                'len' => ['4,50', '用户名只能为4~30个字符!', 'value', 'all'],
                'unique' => ['', '已存在相同的用户名!', 'value', 'all'],
            ],
            'password' => [
                'len' => ['6,18', '请输入6~18位密码!', 'must', 'add'],
            ]
        ],
        'format' => [
            'username' => [
                'function' => ['html_clear', 'all'],
            ],
        ],
        'into' => '',
        'out' => '',
    ];


    protected function base($where) {
        return $this->table('topics_user(A)')
            ->join('topics_user_role(B)', ['B.role_id', 'A.role_id'])
            ->field(['A.*', 'B.name(role_name)'])
            ->where((array)$where);
    }

    public function loadList($where = array(), $limit = 0, $order = '') {
        $list = $this->base($where)
            ->limit($limit)
            ->order($order)
            ->select();
        foreach ($list as $key => $vo) {
            $list[$key]['show_name'] = $vo['username'];
            $list[$key]['avatar'] = $vo['avatar'] ? $vo['avatar'] : ROOT_URL . '/public/topics/images/logo.png';
        }
        return $list;
    }

    public function countList($where = array()) {
        return $this->base($where)->count();
    }

    public function getWhereInfo($where) {
        $info = $this->base($where)->find();
        if(empty($info)) {
            return [];
        }
        $info['show_name'] = $info['username'];
        $info['avatar'] = $info['avatar'] ? $info['avatar'] : ROOT_URL . '/public/topics/images/logo.png';
        return $info;
    }

    protected function _saveBefore($data) {
        if ($data['password']) {
            $data['password'] = md5($data['password']);
        } else {
            unset($data['password']);
        }
        return $data;
    }


    public function jobs() {
        return [
            1 => '销售',
            2 => '市场/市场拓展/公关',
            3 => '商务/采购/贸易',
            4 => '计算机软、硬件/互联网/IT',
            5 => '电子/半导体/仪表仪器',
            6 => '通信技术',
            7 => '客户服务/技术支持',
            8 => '行政/后勤',
            9 => '人力资源',
            10 => '高级管理',
            11 => '生产/加工/制造',
            12 => '质控/安检',
            13 => '工程机械',
            14 => '技工',
            15 => '财会/审计/统计',
            16 => '金融/银行/保险/证券/投资',
            17 => '建筑/房地产/装修/物业',
            18 => '交通/仓储/物流',
            19 => '普通劳动力/家政服务',
            20 => '零售业',
            21 => '教育/培训',
            22 => '咨询/顾问',
            23 => '学术/科研',
            24 => '法律',
            25 => '美术/设计/创意',
            26 => '编辑/文案/传媒/影视/新闻',
            27 => '酒店/餐饮/旅游/娱乐',
            28 => '化工',
            29 => '能源/矿产/地质勘查',
            30 => '医疗/护理/保健/美容',
            31 => '生物/制药/医疗器械',
            32 => '翻译（口译与笔译）',
            33 => '公务员',
            34 => '环境科学/环保',
            35 => '农/林/牧/渔业',
            36 => '兼职/临时/培训生/储备干部',
            37 => '在校学生',
            38 => '其他'
        ];
    }

    /**
     * 生成用户头像
     * @param $userId
     * @param $image
     * @return bool
     */
    public function avatarUser($userId, $image) {
        $url = 'upload/avatar/' . $userId . '/';
        $dir = ROOT_PATH . $url;
        if (!is_dir($dir)) {
            if (!mkdir($dir, 0777, true)) {
                $this->error = '头像目录没有写入权限!';
                return false;
            }
        }
        $parse = explode('.', $image);
        $ext = strtolower(end($parse));
        if (!in_array($ext, ['jpg', 'jpeg', 'png', 'bmp'])) {
            $ext = 'jpg';
        }
        if (strpos($image, 'http') !== false || strpos($image, 'https') !== false) {
            $data = \dux\lib\Http::doGet($image);
            if (empty($data)) {
                $this->error = '头像文件获取失败!';
                return false;
            }
            $image = $dir . 'cache.' . $ext;
            if (!file_put_contents($image, $data)) {
                $this->error = '头像文件无法写入!';
                return false;
            }
        }else {
            $image = realpath(ROOT_PATH . $image);
        }
        $image = new \dux\lib\Image($image);
        $image->thumb(128, 128, 'center');
        if (!$image->output($dir . '128.jpg', 'jpg')) {
            $this->error = '头像保存失败!';
            return false;
        }
        $image->thumb(64, 64, 'center');
        if (!$image->output($dir . '64.jpg', 'jpg')) {
            $this->error = '头像保存失败!';
            return false;
        }
        $image->thumb(32, 32, 'center');
        if (!$image->output($dir . '32.jpg', 'jpg')) {
            $this->error = '头像保存失败!';
            return false;
        }
        $status = target('member/MemberUser')->edit([
            'user_id' => $userId,
            'avatar' => ROOT_URL . '/' . $url . '128.jpg'
        ]);
        if (empty($status)) {
            $this->error = '头像保存失败!';
            return false;
        }
        return true;
    }


}